package vng.wcc.sonph.LauncherGenerator;

import android.content.Context;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

public class CellView extends LinearLayout{

	private static final int COLOR_ORANGE = 0xffd700;

	private IconView icon;
	private CellInfo info;
	private Formatter formatter;
	private TitleView title;

	/**
	 * CellView is a cell on the screen
	 * @param context
	 * @param formatter provides layout information 
	 * @param info information about the cell: icon,title, and intent to launch
	 */
	public CellView(Context context,Formatter formatter,CellInfo info) {
		super(context);
		this.info = info;
		this.formatter = formatter;
		initView();

	}

	private void initView() {
		setViewLayout();
		addChildren();
	}

	private void addChildren() {
		this.addIconView();
		this.addTitleView();
	}

	private void addTitleView() {
		//Set attributes for the title view
		this.title = new TitleView(this.getContext());
		title.setPadding(
				formatter.getTitleLeftPadding(),
				formatter.getTitleRightPadding(),
				formatter.getTitleTopPadding(),
				formatter.getTitleBottomPadding());
		title.setText(info.getTitle());
		title.setGravity(Gravity.CENTER_HORIZONTAL);
		title.setEllipsize(TruncateAt.END);
		title.setFadingEdgeLength(10);
//		title.setTextColor(getResources().getColor(android.R.color.black));
//		title.setBackgroundResource(android.R.color.darker_gray);					

		this.addView(
				title, 
				formatter.getTitleWidth(),
				formatter.getTitleHeight());
		//Add intent to launch on item click
		this.title.setOnClickListener(new OnCellClickListener());

	}

	private void addIconView() {
		this.icon = new IconView(this.getContext());

		icon.setPadding(
				formatter.getIconLeftPadding(), 
				formatter.getIconTopPadding(),
				formatter.getIconRightPadding(),
				formatter.getIconBottomPadding()
		);
		icon.setImageBitmap(info.getIconImage());
		icon.setBackgroundResource(android.R.color.transparent);
		
		this.addView(
				icon, 
				formatter.getIconLayoutWidth(), 
				formatter.getIconLayoutHeight());
		//Add intent to launch on item click
		this.icon.setOnClickListener( new OnCellClickListener());			


	}

	private void setViewLayout() {
		int cellPadding = formatter.getCellPadding();
		this.setPadding(cellPadding,cellPadding,cellPadding,cellPadding);
		this.setOrientation(LinearLayout.VERTICAL);

	}	

	private class OnCellClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {	
			//TODO: why doesnt this code work ?
			CellView.this.icon.setBackgroundColor(COLOR_ORANGE);
			CellView.this.invalidate();
			CellView.this.getContext().startActivity(info.getIntent());
		}
		
	}
}

